<?php
/*
 *  This file is part of TCDB.
 *  
 *  Copyright (C) 2000-2009
 *  Technology Consultant Corps
 *  Grinnell College
 *  Grinnell, IA 50112
 *  tc@grinnell.edu
 *
 *  TCDB is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  TCDB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with TCDB; if not, see <http://www.gnu.org/licenses/>.
 *

 ============================================================================

 * scrape_photo.php -- Contains functions that look at db.grinnell.edu to find
 *		       the requested user's picture
 *
 * Author: C.M. Lubinski
 * Created: 2008-04-19
 * Last edited: 2009-07-10 
 *
 * Edited by Dylan J. Sather, 2009-07-10 -- moved to mysqli extension
 */

function getPictureURL($username)
{
  /***************************************************************
  //------Phase One: Do a Search to find SomeKindofNumber-------//
  ***************************************************************/
  if (!$curl = curl_init("http://db.grinnell.edu/default.asp?" .
			  "transmit=true&email=$username"))
    return "Error; could not curl_init db.grinnell.edu";

  //  Allow us to read the return val rather than printing it
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

  //  Fetch result
  if (!$searchRes = curl_exec($curl))
    return "Problem fetching db.grinnell.edu";
  curl_close($curl);
  

  //  Now we have the search page; we need to scrape it for
  //  "SomeKindofNumber", which indicates $username's id number in
  //  stalkernet. If this system ever changes, this script will not work
  
  $skonPos = strpos($searchRes, "SomeKindofNumber");
  //  Offset to account for SomeKindofNumber'=
  $skonPos += 17;

  while (is_numeric($searchRes[$skonPos])) 
    $skon .= $searchRes[$skonPos++];

  /***************************************************************
  //--Phase Two: Given SKoN, find the photo's "moved" location--//
  ***************************************************************/
  //  Now that we have SomeKindofNumber, we get get the image through
  //  another scrape

  if (!$curl = curl_init("http://db.grinnell.edu/displaydata.asp?" .
			  "SomeKindofNumber=$skon"))
    return "Error; could not curl_init db.grinnell.edu";

  //  Allow us to read the return val rather than printing it
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

  //  Fetch result
  if (!$userRes = curl_exec($curl))
    return "Problem fetching image page from db.grinnell.edu";
  curl_close($curl);

  //  Again, we have another key word; at the moment, all of the db images
  //  are stored in moved/, which will serve as something easy to search
  //  for
  $ret = $userRes;

  if (!$movedPos = strpos($userRes, "src=\"moved/"))
    return "User no longer exists in Stalkernet.";
  //  Offset to account for src="moved/
  $movedPos += 11;

  while (is_numeric($userRes[$movedPos])) 
    $imageNum .= $userRes[$movedPos++];

  return "http://db.grinnell.edu/moved/$imageNum.jpg";
}

function placeImageInDB($image, $type, $userId, $buffer = false)
{
  //  Though I love replace, we can't use it here as it would get rid of
  //  the buffer or non-buffered images

  $query = sprintf("SELECT user_id
		    FROM images
		    WHERE user_id = '%s'",
		mysqli_real_escape_string($mysqli, $userId));
		
  $result = $mysqli->query($query, MYSQLI_STORE_RESULT);

  if ($result->num_rows == 0)
    $query = "INSERT INTO images SET user_id = $userId, ";
  else
    $query = "UPDATE images SET ";

  // Do we need this? (Dylan, 2009-07-10)
  $image = addslashes($image);

  if ($buffer)
    $query .= "mime_buffer = '$type', picture_data_buffer = '$image'";
  else
    $query .= "mime='$type', picture_data='$image', mime_buffer = NULL,
	      picture_data_buffer = NULL";

  if ($replace == 0)
    $query .= " WHERE user_id=$userId";

  if(!$mysqli->query($query, MYSQLI_STORE_RESULT))
    return "MySQL: " . mysqli_connect_error();
}

function moveImageFromBuffer($userId, $accept)
{
  switch ($accept)
  {
    case "accept":
	$query = sprintf("UPDATE images 
			  SET picture_data = picture_data_buffer,
			      mime = mime_buffer, picture_data_buffer = NULL,
			      mime_buffer = NULL 
			  WHERE user_id = '%s'",
		      mysqli_real_escape_string($mysqli, $userId));

	if (!$result->query($query, MYSQLI_STORE_RESULT))
	    return "MySQL: " . mysqli_connect_error(); 
	break;
    case "reject":
	$query = sprintf("UPDATE images 
			  SET picture_data_buffer = NULL, 
			      mime_buffer = NULL
			  WHERE user_id = '%s'",
		      mysqli_real_escape_string($mysqli, $userId));

	if (!$result->query($query, MYSQLI_STORE_RESULT))
	    return "MySQL: " . mysqli_connect_error();
	break;
    default:
	break;
  }
} 

function placeDataInDB($imageURL, $userId)
{
  //  Fetch image
  if (!$curl = curl_init($imageURL))
    return "Error; could not curl_init db.grinnell.edu";

  //  Allow us to read the return val rather than printing it
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

  //  Fetch result
  if (!$image = curl_exec($curl))
    return "Problem fetching info page from db.grinnell.edu";
  curl_close($curl);

  return placeImageInDB($image, "image/jpeg", $userId);
}

function retrieveImage($id, $buffer = false, $mysqli)
{
  $query = sprintf("SELECT " . ($buffer ? "picture_data_buffer" : "picture_data") . ", 
		    mime
		    FROM images
		    WHERE user_id = '%s'",
		mysqli_real_escape_string($mysqli, $id));

  if ($result = $mysqli->query($query, MYSQLI_STORE_RESULT)) {
      return $result->fetch_row();
  }
  else
      return false;

  $result->free();
}

?>
